#!/usr/bin/env python
# -*- encoding:    utf-8 -*-
# Author      :    yao low_design@163.com
# Date        :    2025/02/17 22:16:56


from odoo.exceptions import ValidationError, UserError
from odoo import _, api, fields, models
from ..__init__ import with_redis_client
from .redis_content import RedisClient
import logging

_logger = logging.getLogger(__name__)


class RedisConfig(models.Model):
    _name = 'redis.config'
    _description = 'Redis Config'

    name = fields.Char(string='名称', required=True)
    host = fields.Char(string='地址', required=True)
    port = fields.Integer(string='端口', required=True)
    password = fields.Char(string='密码')
    db = fields.Integer(string='DB', required=True)
    state = fields.Selection([
        ('draft', '草稿'),
        ('confirm', '确认'),
        ('stop', ' 停用'),
    ], string='状态', default='draft')

    def do_confirm(self):
        """
        确认操作

        """
        for item in self:
            if item.host and item.port and item.db:
                item.write({'state': 'confirm'})

    def do_stop(self):
        """
        停止操作
        """
        self.write({'state': 'stop'})

    def get_client(self):
        try:
            redis = RedisClient(
                host=self.host,
                port=self.port,
                db=self.db,
                password=self.password,
            )
            # 测试连接
            if redis.redis_conn.ping():
                return redis
        except Exception as e:
            _logger.error(f"Redis connection error: {str(e)}")
            raise UserError(f'连接失败: {str(e)}')

    @api.with_redis_client
    def test(self, redis_client=None):
        """
        测试连接
        """
        if redis_client:
            if redis_client.redis_conn.ping():
                self.env['bus.bus']._sendone('redis.config', {

                })
        return False
